/*
 * Deptree.cpp
 *
 *  Created on: Dec 18, 2014
 *      Author: Phong
 */

#include "Deptree.h"
#include "Depstruct.h"
#include <iostream>
using namespace std;

Deptree::Deptree(int nWords) {
	nNodes = nWords;
	word = new int[nNodes]();
	pos = new int[nNodes]();
	cap = new int[nNodes]();
	parent = new int[nNodes]();
	dir = new int[nNodes]();
	deprel = new int[nNodes]();
	ds = NULL;

	nChildren = new int*[nNodes];
	children = new int**[nNodes];
	for (int i = 0; i < nNodes; i++) {
		nChildren[i] = new int[nNodes]();
		children[i] = new int*[2];
		children[i][0] = new int[nNodes]();
		children[i][1] = new int[nNodes]();
	}
    
    refCount = 1;
    
    outer = NULL;
    pOuter = NULL;
    EOCOuter = NULL;
    gradO = NULL;
    gradpO = NULL;
    gradEOCO = NULL;
    
    gZdr = NULL;
    gZpos = NULL;
    gZword = NULL;
    gZcap = NULL;
    gZ_EOC = NULL;
    
    phraseISums = NULL;
    sums = NULL;
    
    gradheadI = NULL;
    gradphraseI = NULL;
    headInner = NULL;
    phraseInner = NULL;
    
    deprelProb = NULL;
    posProb = NULL;
    capProb = NULL;
    wordProb = NULL;
    EOCProb = NULL;
}

Deptree::~Deptree() {
    for (int i = 0; i < nNodes; i++) {
        delete[] children[i][0];
        delete[] children[i][1];
        delete[] children[i];
        delete[] nChildren[i];
    }
    delete[] children;
    delete[] nChildren;
    delete[] word;
    delete[] pos;
    delete[] deprel;
    delete[] cap;
    delete[] parent;
    delete[] dir;
}

void Deptree::free(Deptree *tree) {
    tree->refCount--;
    if (tree->refCount == 0) delete tree;
}

Deptree* Deptree::share() {
    refCount++;
    return this;
}

string Deptree::toString(Dictionary* vocaDic, Dictionary* posDic, Dictionary* deprelDic) {
	string str;
	for (int i = 1; i < nNodes; i++) {
		str	+= to_string(i) + "\t"
				+ vocaDic->id2word[word[i]] + "\t"
				+ to_string(cap[i])+ "\t"
				+ posDic->id2word[pos[i]] + "\t"
				+ to_string(parent[i]) + "\t"
				+ to_string(dir[i]) + "\t"
				+ deprelDic->id2word[deprel[i]] + "\n";
	}

	return str;
}

void Deptree::freeTempArrays(){
    Matrix::free(outer, nNodes);
    Matrix::free(pOuter, nNodes);
    Matrix::free(EOCOuter, 2, nNodes);
    Matrix::free(gradO, nNodes);
    Matrix::free(gradpO, nNodes);
    Matrix::free(gradEOCO, 2, nNodes);

    Matrix::free(deprelProb, nNodes);
    Matrix::free(posProb, nNodes);
    Matrix::free(wordProb, nNodes);
    Matrix::free(capProb, nNodes);
    Matrix::free(EOCProb, 2, nNodes);
    
    Matrix::free(phraseISums, 2, nNodes);
    Matrix::free(sums, 2, nNodes);
    
    Matrix::free(gradheadI, nNodes);
    Matrix::free(gradphraseI, nNodes);
    Matrix::free(headInner, nNodes);
    Matrix::free(phraseInner, nNodes);
}


